import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:my_desk_flutter/net/interceptors/auth_interceptor.dart';
import 'package:my_desk_flutter/storage/local_file_provider.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'dio_client.g.dart';

@Riverpod(keepAlive: true)
Dio dioClient(DioClientRef ref) {
  Dio dio = Dio(
    BaseOptions(
        baseUrl: 'https://api.91bus.cn',
        connectTimeout: const Duration(seconds: 30),
        receiveTimeout: const Duration(seconds: 30),
        sendTimeout: const Duration(seconds: 30),
        headers: {
          'User-Agent':
              'Mozilla/5.0 (Linux; Android 7.1.2; SM-G955N Build/NRD90M.G955NKSU1AQDC; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/92.0.4515.131 Mobile Safari/537.36 MicroMessenger/8.0.27.2220(0x28001B36) WeChat/arm32 Weixin NetType/WIFI Language/zh_CN ABI/arm32 MiniProgramEnv/android',
          'usertoken': 'DF030674BD4ED929009BE33F1304D29867F5C46C815C88D8',
        }),
  );
  final cookieJar = PersistCookieJar(
      storage: FileStorage('${ref.read(localFileProvider).path}/cookies'));
  dio.interceptors.add(CookieManager(cookieJar));
  dio.interceptors.add(
    PrettyDioLogger(
      requestHeader: true,
      requestBody: true,
      responseBody: true,
      responseHeader: false,
      compact: false,
    ),
  );
  dio.interceptors.add(ref.read(authInterceptorProvider));
  // getApplicationCacheDirectory()

  return dio;
}

class DioClient {
  Dio dioClient() {
    Dio dio = Dio(
      BaseOptions(
          baseUrl: 'https://api.91bus.cn',
          connectTimeout: const Duration(seconds: 30),
          receiveTimeout: const Duration(seconds: 30),
          sendTimeout: const Duration(seconds: 30),
          headers: {
            'User-Agent':
                'Mozilla/5.0 (Linux; Android 7.1.2; SM-G955N Build/NRD90M.G955NKSU1AQDC; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/92.0.4515.131 Mobile Safari/537.36 MicroMessenger/8.0.27.2220(0x28001B36) WeChat/arm32 Weixin NetType/WIFI Language/zh_CN ABI/arm32 MiniProgramEnv/android',
            'usertoken': 'DF030674BD4ED929009BE33F1304D29867F5C46C815C88D8',
          }),
    );

    final cookieJar = CookieJar();
    dio.interceptors.add(CookieManager(cookieJar));
    dio.interceptors.add(
      PrettyDioLogger(
        requestHeader: true,
        requestBody: true,
        responseBody: true,
        responseHeader: false,
        compact: false,
      ),
    );
    // dio.interceptors.add(ref.read(authInterceptorProvider));

    return dio;
  }
}
